<template>
  <div>
    <el-button type="danger" @click="showEdit('add')">新增分类</el-button>
    <el-row :gutter="10" :style="{ 'margin-top': '10px' }">
      <el-col :span="14">
        <el-card class="box_card">
          <template #header>
            <div class="card_header">
              <span>专题</span>
            </div>
          </template>
          <Table ref="dataTableRef" @rowClick="rowClick" :columns="columns" :showPagination="true"
            :dataSource="tableData" :fetch="loadDataList" :options="tableOptions">
            <template #cover="{ index, row }">
              <Cover :cover="row.cover"></Cover>
            </template>
            <template #op="{ index, row }">
              <div class="op">
                <a href="javascript:void(0)" @click="showEdit('update', row)" class="a-link"
                  v-if="userInfo.userId == row.userId">修改</a>
                <span v-else> -- </span>
                <el-divider direction="vertical"></el-divider>
                <a href="javascript:void(0)" @click="del(row)" class="a-link"
                  v-if="userInfo.userId == row.userId">删除</a>
                <span v-else> -- </span>
              </div>
            </template>
          </Table>
        </el-card>

      </el-col>
      <el-col :span="10">
        <el-card class="box_card">
          <template #header>
            <div class="card_header">
              <span>专题文章</span>
            </div>
          </template>
          <div :style="{ 'margin-bottom': '5px' }">
            <el-alert title="红色代表< 草稿 > , 绿色代表< 已发布 >拖动文件更改排序" type="info" show-icon :closable="false">
            </el-alert>
          </div>
          <div class="special_blog_tree">
            <el-tree class="tree-panel" ref="refTree" :data="blogList" defaultExpandAll node-key="blogId"
              :expand-on-click-node="false" :props="treeProps" :highlight-current="true" draggable
              @node-drop="blogDrag">
              <template #default="{ node, data }">
                <span class="custom-node-style">
                  <span class="node-title">
                    <span v-if="data.status == 0" :style="{ 'color': 'red', 'font-size': '13px' }">{{ data.title
                      }}</span>
                    <span v-else :style="{ 'color': 'green', 'font-size': '13px' }">{{ data.title }}</span>
                  </span>
                  <span class="node-.op">
                    <template v-if="data.blogId === '0'">
                      <a class="a-link" href="javascript:void(0)" @click="editBlog('add', data)">新增文章</a>
                    </template>
                    <template v-else>
                      <a class="a-link" href="javascript:void(0)" @click="showDetail(data)">预览</a>
                      <el-divider direction="vertical" />
                      <a class="a-link" href="javascript:void(0)" @click="editBlog('edit', data)"
                        v-if="userInfo.userId == data.userId">修改</a>
                      <span v-else> -- </span>
                      <el-divider direction="vertical" />
                      <a class="a-link" href="javascript:void(0)" @click="delBlog(data)"
                        v-if="userInfo.userId == data.userId">删除</a>
                      <span v-else> -- </span>
                      <el-divider direction="vertical" />
                      <a class="a-link" href="javascript:void(0)" @click="editBlog('add', data)">新增下级文章</a>
                    </template>
                  </span>
                </span>
              </template>
            </el-tree>
          </div>
        </el-card>

      </el-col>

    </el-row>

    <Dialog width="800px" :show="dialogConfig.show" @close="dialogConfig.show = false" :title="dialogConfig.title"
      :buttons="dialogConfig.buttons">
      <el-form :model=formData :rules="rules" ref="formDataRef" label-width="60px">
        <el-form-item label="名称" prop="categoryName">
          <el-input placeholder="请输入名称" v-model="formData.categoryName" size="large">
          </el-input>
        </el-form-item>
        <el-form-item label="封面" prop="cover">
          <CoverUpload v-model="formData.cover"></CoverUpload>
        </el-form-item>
        <el-form-item label="简介" prop="des">
          <el-input type="textarea" placeholder="请输入简介" v-model="formData.categoryDesc" size="large"
            :autosize="{ minRows: 4, maxRows: 4 }">
          </el-input>
        </el-form-item>
      </el-form>
    </Dialog>

    <BlogEdit ref="blogEditRef" @callback="saveBlogCallBack"></BlogEdit>
    <BlogDetail ref="blogDetailRef"></BlogDetail>
  </div>
</template>

<script setup>
import BlogEdit from './BlogEdit.vue';
import BlogDetail from './BlogDetail.vue'
import { getCurrentInstance, nextTick, reactive, ref } from 'vue';
import Cover from '../../components/Cover.vue';
const { proxy } = getCurrentInstance()
const userInfo = ref(proxy.VueCookies.get('userInfo') || {})

const api = {
  'loadDataList': '/category/loadCategory4Special',
  'saveCategory': '/category/saveCategory4Special',
  'delCategory': '/category/delCategory4Special',
  'getSpecialInfo': '/blog/getSpecialInfo',
  'delBlog': '/blog/recoveryBlog',
  'updateSpecialBlogSort': '/blog/updateSpecialBlogSort'
}
const columns = [{
  label: '封面',
  prop: 'cover',
  width: 100,
  scopedSlots: 'cover'
},
{
  label: '名称',
  prop: 'categoryName',
  width: 200
},
{
  label: '简介',
  prop: 'categoryDesc',
},
{
  label: '博客数量',
  prop: 'blogCount',
  width: 100
},
{
  label: '操作',
  prop: 'op',
  width: 100,
  scopedSlots: 'op',
},
]

const tableData = reactive({})
const tableOptions = {
  exHeight: 135,
}


const dataTableRef = ref(null);
const currentCategoryId = ref(null);
const loadDataList = async () => {
  let res = await proxy.Request({
    url: api.loadDataList
  })
  if (!res) {
    return
  }
  Object.assign(tableData, res.data)
  if (currentCategoryId.value == null && res.data.list.length > 0) {
    currentCategoryId.value = res.data.list[0].categoryId
    loadAllList();

  }
  nextTick(() => {
    dataTableRef.value.setCurrentRow('categoryId', currentCategoryId.value)
  })
}

const dialogConfig = reactive({
  show: false,
  title: '标题',
  buttons: [{
    type: 'danger',
    text: '确定',
    click: (e) => {
      submitForm();
    }
  }]
})


const formData = ref({})
const rules = {
  categoryName: [{
    required: 'true',
    message: '请输入分类名称'
  }]
};
const formDataRef = ref()
const showEdit = (type, data) => {
  dialogConfig.show = true
  nextTick(() => {
    formDataRef.value.resetFields();
    if (type == 'add') {
      dialogConfig.title = '新增分类'
      formData.value = {};
      // Object.assign(formDate,{});
    } else if (type == 'update') {
      dialogConfig.title = '编辑分类'
      // Object.assign(formData, data)
      formData.value = data;

    }
  })
}

const submitForm = () => {
  formDataRef.value.validate(async (valid) => {
    if (!valid) {
      return;
    }
    let params = {}
    Object.assign(params, formData.value)
    let res = await proxy.Request({
      url: api.saveCategory,
      params,
    })
    if (!res) {
      return;
    }
    dialogConfig.show = false;
    proxy.Message.success('保存成功');
    loadDataList();
  })
}


// 删除 
const del = (data) => {
  proxy.Confirm(`你确定要删除${data.categoryName}吗？`, async () => {
    let res = await proxy.Request({
      url: api.delCategory,
      params: {
        categoryId: data.categoryId
      }
    })
    if (!res) {
      return;
    }
    loadDataList();
    currentCategoryId.value = null;
  })
}

// 专题树
// 获取专题文章
const rowClick = (row) => {
  currentCategoryId.value = row.categoryId,
    loadAllList(row.categoryId)

}

const blogList = ref([]);
const loadAllList = async (categoryId) => {
  let res = await proxy.Request({
    url: api.getSpecialInfo,
    params: {
      categoryId: currentCategoryId.value,
      showType: '1'
    }
  })
  blogList.value = res.data
}
// 属性展示专题
const treeProps = {
  children: 'children',
  label: 'title',
  value: 'blogId'
}

const blogEditRef = ref(null)
// 新增 修改 专题博客
const editBlog = (type, data) => {
  blogEditRef.value.init(type, data);
}

// 保存博客专题回调
const saveBlogCallBack = () => {
  loadAllList();
};


// 删除博客
// 删除博客
const delBlog = (data) => {
  proxy.Confirm(`你确定要删除【${data.title}】吗？`, async () => {
    let res = await proxy.Request({
      url: api.delBlog,
      params: {
        blogId: data.blogId
      }
    })
    if (!res) {
      return;
    }
    loadAllList();
  })
}

const blogDrag = async (draggingNode, dropNode, dropType, ev) => {
  // 拖动改变排序，修改父级
  let parentNode = null;

  if (dropType == "inner") {
    // 拖入某个节点内，修改父级节点为目标节点，同时修改目标节点下的所有子节点的排序
    parentNode = dropNode;
  } else {
    // 拖入之前，之后，修改被拖动的节点的父节点为目标节点的父节点，同时修改目标节点父节点下所有的子节点的排序
    parentNode = dropNode.parent;
  }

  // 操作的节点ID
  const blogId = draggingNode.data.blogId;
  const pBlogId = parentNode.data.blogId;

  // 需要从新排序的博客ID
  const blogIds = [];
  parentNode.childNodes.forEach((element) => {
    blogIds.push(element.data.blogId);
  });

  let params = {
    blogId,
    pBlogId,
    blogIds: blogIds.join(","),
  };

  let result = await proxy.Request({
    url: api.updateSpecialBlogSort,
    params,
  });

  if (!result) {
    return;
  }
  loadAllList();
};

// 预览详情
const blogDetailRef = ref(null);
const showDetail = (data) => {
  blogDetailRef.value.showDetail(data);
}
</script>

<style lang="scss">
.tree-panel {
  height: calc(100vh - 295px);
  overflow: auto;

  .el-tree-node__content {
    flex: 1;
  }

  .custom-node-style {
    flex: 1;
    display: flex;
    justify-content: space-between;
  }
}
</style>